package com.lzp.java.concurrent.buildcache;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author lzp
 * @Description: 压力测试类
 * @date 2021/3/14
 */
public class CacheTest {
    private static final Cache7 cache = new Cache7(new ComputableImpl());
    private static final CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(1000);
        for (int i = 0; i < 1000; i++) {
            pool.submit(() -> {
                try {
                    System.out.println(Thread.currentThread() + "开始等待");
                    latch.await();
                    System.out.println(Thread.currentThread() + "开始计算，当前时间是" + DateFormatter.dateFormat.get().format(new Date()));
                    System.out.println(cache.compute("key"));
                    System.out.println(Thread.currentThread() + "使用缓存结束");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        TimeUnit.SECONDS.sleep(3);
        long start = System.currentTimeMillis();
        latch.countDown();
        pool.shutdown();
        while (!pool.isTerminated()) {
        }
        long end = System.currentTimeMillis();
        System.out.println((end - start));
    }

}

class DateFormatter {
    // private static ThreadLocal<SimpleDateFormat> dateFormatter = ThreadLocal.withInitial(
    //         () -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    // );

    public static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }

        @Override
        public SimpleDateFormat get() {
            return super.get();
        }
    };

}
